package com.tarena.security.admin.service.impl;


import com.tarena.security.admin.converter.AppConverter;
import com.tarena.security.admin.entity.db.App;
import com.tarena.security.admin.entity.param.AppParam;
import com.tarena.security.admin.entity.query.AppQuery;
import com.tarena.security.admin.errorenum.ResultEnum;
import com.tarena.security.admin.exception.SecurityAdminBusinessException;
import com.tarena.security.admin.persists.repository.AppRepository;
import com.tarena.security.admin.service.IAppService;

import java.time.LocalDateTime;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * app 服务实现类
 * </p>
 *
 * @author Ly
 * @since 2023-04-10
 */
@Service
public class AppServiceImpl  implements IAppService {

    private static final Logger logger=LoggerFactory.getLogger(AppServiceImpl.class);
    @Resource
    private AppRepository appRepository;

    @Override public void addNewApp(AppParam param) {
        int count=appRepository.getAppCountByName(param.getName());
        logger.info("查询结果为：{}",count);
        if (count>0){
            throw new SecurityAdminBusinessException(ResultEnum.SYS_APP_ALREADY_EXISTS);
        }
        long l = System.currentTimeMillis();
        App app= AppConverter.convertParamToModel(param);
        app.setCreateTime(l);
        app.setUpdateTime(l);
        count=appRepository.addNewApp(app);
        if (count!=1){
            throw new SecurityAdminBusinessException(ResultEnum.SYSTEM_ERROR);
        }
    }

    @Override public List<App> getAppList(AppQuery query) {
        List<App> list =appRepository.getAppList(query);
        return list;
    }

    @Override public void updateByID(AppParam param) {
        logger.info("AppParam:{}",param);
        App app=appRepository.getAppById(param.getId());
        if (app==null){
            throw new SecurityAdminBusinessException(ResultEnum.SYS_APP_NON_EXISTENT);
        }
        int count = appRepository.getAppCountByName(param.getName());
        if (count!=0){
            throw new SecurityAdminBusinessException(ResultEnum.SYS_APP_ALREADY_EXISTS);
        }
        app= AppConverter.convertParamToModel(param);
        app.setUpdateTime(System.currentTimeMillis());
        logger.info("App:{}",app);

        int row=appRepository.updateByID(app);
        if (row!=1){
            throw new SecurityAdminBusinessException(ResultEnum.SYSTEM_ERROR);
        }
    }

    @Override public App getAppById(Integer id) {
        return appRepository.getAppById(id);
    }

    @Override public void deleteAppById(Integer[] id) {
        int i=appRepository.deleteById(id);
    }
}
